<template>
  <q-dialog v-model="show" persistent>
    <q-card style="min-width: 350px; padding: 20px 10px">
      <q-card-section>
        <div class="text-h6">添加歌曲</div>
      </q-card-section>

      <q-card-section class="q-pt-none">
      <q-form
          @submit="isEdit ?  editMusic():createMusic() "
          class="q-gutter-md"
      >
        <q-card-section>
        <q-input
            dense
            v-model="music.name"
            label="歌曲名"
            autofocus
            :rules="[ val => val && val.length > 0 || '请输入歌曲名!']"
            @keyup.enter="show = false"
        />



        <q-input
            outlined
            v-model="music.description"
            label="简介"
            autofocus
            :rules="[ val => val && val.length > 0 || '请输入简介!']"
            @keyup.enter="show = false"
        />
        </q-card-section>

        <q-card-section>
          <artist-selector v-model:artistList="music.artistList" />
        </q-card-section>
        <q-card-section>
          <uploader lable="上传音乐" v-model:file="music.file"/>
        </q-card-section>

      <q-card-actions align="right" class="text-primary">
        <q-btn label="确认" type="submit" color="primary"/>
        <q-btn flat label="取消" v-close-popup />
      </q-card-actions>
      </q-form>
      </q-card-section>
    </q-card>
  </q-dialog>
</template>

<script setup>


import {reactive, ref} from "vue";
import PromptInfo from "../../utils/notification.js";
import musicApi from "../../api/music.js";
import Uploader from '../../components/Uploader.vue';
import ArtistSelector from '../../components/ArtistSelector.vue'
const props=defineProps({
  data:{
    type:Object,
    default() {
      return null;
    }
  }
});

const show=ref(true)

const file=ref(null)

const isEdit=ref(Boolean(props.data))

const music=reactive(props.data||{name:'',description:'',file:null,artistList:[]})

const emmit=defineEmits(['create-success','edit-success']);
const createMusic=()=>{
   const createdMusicRequest={
     ...music,
     fileId:music.file.id,
     artistIds: music.artistList.length===0?[]:music.artistList.map(item=>item.id)
   }
  musicApi.create(createdMusicRequest).then(createMusic=>{
    show.value=false;
    PromptInfo.success(`音乐《${createMusic.name}》创建成功`)
    emmit('create-success');
  })

}

const editMusic=()=>{
  const updateMusicRequest={
    ...music,
    fileId:music.file.id,
    artistIds: music.artistList.length===0?[]:music.artistList.map(item=>item.id)
  }
  musicApi.update(music.id,updateMusicRequest).then(updateMusic=>{
    show.value=false
    PromptInfo.success(`音乐《${updateMusic.name}》更新成功`)
    emmit('edit-success')
  })
}
</script>

<style scoped>

</style>